<template>
  <div class="back-to-top-container">
    <transition name="fade">
      <button 
        v-show="isVisible"
        class="back-to-top-btn"
        @click="scrollToTop"
      >
        ↑ 回顶部
      </button>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'BackToTop',
  data() {
    return {
      isVisible: false
    };
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      // 判断是否滚动到底部（考虑兼容性）
      const scrollPosition = window.innerHeight + document.documentElement.scrollTop;
      this.isVisible = scrollPosition >= document.documentElement.scrollHeight - 100;
    },
    scrollToTop() {
      // 平滑滚动到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
  }
};
</script>

<style scoped>
.back-to-top-container {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 1000;
}

.back-to-top-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: opacity 0.3s;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>